package com.gzdh.dishrecognition.ui.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.greendao.dao.MacMainpSbruanDinnerEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.ProductConst;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.emu.PeripheralDeviceEmus;
import com.gzdh.dishrecognition.emu.ReadCardTypeEmus;
import com.gzdh.dishrecognition.entity.MacMainpSbruanDinnerEntity;
import com.gzdh.dishrecognition.event.CartEvent;
import com.gzdh.dishrecognition.event.TimeEvent;
import com.gzdh.dishrecognition.model.ProductCartModel;
import com.gzdh.dishrecognition.ui.activity.ReportActivity;
import com.gzdh.dishrecognition.ui.activity.ScanTakeFoodActivity;
import com.gzdh.dishrecognition.ui.activity.SelectPayActivity;
import com.gzdh.dishrecognition.ui.adapter.LeftBmcmAdapter;
import com.gzdh.dishrecognition.ui.adapter.inputNumber.InputNumberAdapter;
import com.gzdh.dishrecognition.ui.pre.ShowCardPre;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.KeyAdd;
import com.gzdh.dishrecognition.util.ProductSUtils;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.jiebao.util.CardReaderUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class InputNumberView extends LinearLayout {

    private final Cache<String,String> cache = CacheBuilder.newBuilder().maximumSize(1000).
            expireAfterWrite(3, TimeUnit.SECONDS).build();
    private final Context mContext;

    private TextView netStatusRv;

    private TextView timeTv;

    private TextView cardMsgTv;

    private NumberKeyView numberKey;

    private TextView priceTv;

    private TextView payBut;

    private TextView cancel_button;

    private TextView addBtn;

    private RecyclerView bmcmRv;

    private TextView amountTv;

    private ImageView scanTakeBtn;

    private EditText inputNumberEditText;

    private ShowCardPre showCardPre;

    private LinearLayout rightKeyboardLinearLayout;

    public void setShowCardPre(ShowCardPre showCardPre) {
        this.showCardPre = showCardPre;
    }

    private InputNumberAdapter inputNumberAdapter;

    private MacMainpSbruanDinnerEntity macMainpSbruanDinnerEntity;
    private final MacMainpSbruanDinnerEntityDao macMainpSbruanDinnerEntityDao = AppContext.getInstance().getDaoSession().getMacMainpSbruanDinnerEntityDao();

    public InputNumberView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_mode_input_number, this, true);
        mContext = context;
        initView();
        initDate();
    }

    public void clear() {
        mProductCartModel = new ProductCartModel();
        mProductCartModelList = new ArrayList<>();
        ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
    }

    @SuppressLint("SetTextI18n")
    public void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (SysConstConfig.getInstance().isAllowCard())
            if(SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.defaultType) {
                CardReaderDevice.getInstance().initCardReader();
            }
        clear();
        if (ProductConst.getInstance().getProductCartModelList().size() == 0) {
            priceTv.setText("￥0.00");
            numberKey.clear();
        }
    }

    public void disWindows() {

    }

    private void initView() {
        EventBus.getDefault().register(this);
        rightKeyboardLinearLayout = findViewById(R.id.rightKeyboard);
        netStatusRv = findViewById(R.id.netStatusRv);
        timeTv = findViewById(R.id.timeTv);
        cardMsgTv = findViewById(R.id.cardMsgTv);
        numberKey = findViewById(R.id.numberKey);
        priceTv = findViewById(R.id.tv_price);
        payBut = findViewById(R.id.payBut);
        cancel_button = findViewById(R.id.cancel_button);
        bmcmRv = findViewById(R.id.bmcmRv);
        amountTv = findViewById(R.id.amountTv);
        addBtn = findViewById(R.id.add_button);
        inputNumberEditText = findViewById(R.id.inputNumberEdit);
        inputNumberEditText.setText("0");
        inputNumberEditText.setFocusable(false);
        inputNumberEditText.setFocusableInTouchMode(false);
        inputNumberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int after) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString();
                String price = priceTv.getText().toString().substring(1);
                if("".equals(text)) {
                    text = "0";
                }
                if(text.equals(price)) {
                    return;
                }
                String endInput = text.substring(text.length() - 1);
                String originalInput = text.substring(0, text.length() - 1);
                if("".equals(originalInput)) {
                    originalInput = "0";
                }
                String keyNum = KeyAdd.getKeyNum(originalInput, endInput);
                setPrice(keyNum);
                numberKey.setVal(keyNum);
                if(!price.equals(inputNumberEditText.getText().toString())) {
                    inputNumberEditText.setText(keyNum);
                    inputNumberEditText.clearFocus();
                    inputNumberEditText.requestFocus();
                }
            }
        });
        inputNumberEditText.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 处理回车事件
                if(cache.getIfPresent("enterKey") != null) {
                    return true;
                }
                cache.put("enterKey", inputNumberEditText.getText().toString());
                payBut.performClick();
                return true;
            }
            if (keyCode == KeyEvent.KEYCODE_F1 && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 处理查询事件
                ReportActivity.startAndSelectItem(mContext, "1");
                return true;
            }
            if (keyCode == KeyEvent.KEYCODE_F3 && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 处理取消事件
                cancel_button.performClick();
                return true;
            }
            if (keyCode == KeyEvent.KEYCODE_NUMPAD_ADD && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 处理+号事件
                addBtn.performClick();
                return true;
            }
            return false;
        });

        inputNumberAdapter = new InputNumberAdapter(mContext);
        RecyclerView cartRv = findViewById(R.id.cartRv);
        GridLayoutManager productLayoutManager = new GridLayoutManager(mContext, SysConstConfig.getInstance().getFoodsMenuRow());
        productLayoutManager.setOrientation(RecyclerView.VERTICAL);
        cartRv.setLayoutManager(productLayoutManager);
        cartRv.setAdapter(inputNumberAdapter);
        cartRv.addItemDecoration(new MyGridSpacingItemDecoration(3));
        inputNumberAdapter.setOnReshow(() -> {
            mProductCartModelList = inputNumberAdapter.getProductCartModelList();
            List<ProductCartModel> productCartModelList = JSONArray.parseArray(JSONArray.toJSONString(mProductCartModelList), ProductCartModel.class);
            if (mProductCartModel != null && !"".equals(mProductCartModel.getPrice()) && new BigDecimal(mProductCartModel.getPrice()).compareTo(new BigDecimal(0)) > 0)
                productCartModelList.add(mProductCartModel);
            ProductConst.getInstance().setProductCartModelList(productCartModelList);
            EventBus.getDefault().post(new CartEvent());
        });
        //扫码领餐
        scanTakeBtn = findViewById(R.id.scanTakeBtn);
        if(!SysConstConfig.getInstance().isScanTake()) {
            scanTakeBtn.setVisibility(View.GONE);
        }
        scanTakeBtn.setOnClickListener(view -> {
            if(cache.getIfPresent("scanTake") != null) {
                return;
            }
            cache.put("scanTake", String.valueOf(System.currentTimeMillis()));
            ScanTakeFoodActivity.start(mContext);
        });
        new Thread(() -> {
            try {
                Thread.sleep(3000);
                ((Activity) mContext).runOnUiThread(() -> {
                    inputNumberEditText.setFocusable(true);
                    inputNumberEditText.setFocusableInTouchMode(true);
                    inputNumberEditText.setOnFocusChangeListener((v, hasFocus) -> {
                        if (hasFocus) {
                            // 获取EditText的文本长度，并将光标移动到末尾
                            int length = inputNumberEditText.getText().length();
                            Selection.setSelection(inputNumberEditText.getText(), length);
                        }
                    });
                    inputNumberEditText.requestFocus();
                });
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    LeftBmcmAdapter leftBmcmAdapter;

    private ProductCartModel mProductCartModel = new ProductCartModel();
    private List<ProductCartModel> mProductCartModelList = new ArrayList<>();

    @SuppressLint("SetTextI18n")
    private void initDate() {
        numberKey.setNumberKeyListener((cashStr, key) -> {
            setPrice(cashStr);
            inputNumberEditText.setText(cashStr);
            inputNumberEditText.clearFocus();
            inputNumberEditText.requestFocus();
        });

        payBut.setOnClickListener(view -> {
            if(new android.icu.math.BigDecimal(ProductConst.getInstance().getProductCartPrice()).compareTo(new android.icu.math.BigDecimal(0)) <= 0) {
                Toast.makeText(mContext,"请确认支付金额", Toast.LENGTH_SHORT).show();
                return;
            }
            String cacheValue = cache.getIfPresent("isSubmit");
            if(cacheValue != null) {
                return;
            }
            cache.put("isSubmit", String.valueOf(System.currentTimeMillis()));
            SelectPayActivity.startAct(mContext);
        });

        cancel_button.setOnClickListener(view -> {
            priceTv.setText("￥0.00");
            numberKey.clear();
            mProductCartModelList = new ArrayList<>();
            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
            EventBus.getDefault().post(new CartEvent());
        });
        addBtn.setOnClickListener(view -> {
            if(new BigDecimal(mProductCartModel.getPrice()).compareTo(new BigDecimal(0)) > 0) {
                mProductCartModelList.add(mProductCartModel);
                mProductCartModel = new ProductCartModel();
                numberKey.clear();
            }
        });

        leftBmcmAdapter = new LeftBmcmAdapter(mContext);
        List<MacMainpSbruanDinnerEntity> macMainpSbruanDinnerEntityList = macMainpSbruanDinnerEntityDao.loadAll();
        ProductSUtils.setSbruanDinnerName(macMainpSbruanDinnerEntityList);
        leftBmcmAdapter.setList(macMainpSbruanDinnerEntityList);

        GridLayoutManager bmcmManager = new GridLayoutManager(mContext, 4);
        bmcmManager.setOrientation(RecyclerView.VERTICAL);
        bmcmRv.setLayoutManager(bmcmManager);
        bmcmRv.setAdapter(leftBmcmAdapter);
        bmcmRv.addItemDecoration(new MyGridSpacingItemDecoration(3));

//        leftBmcmAdapter.setUserOnClick(bmcmEntity -> selectBmcm(bmcmEntity));
    }

    private void setPrice(String price) {
        priceTv.setText(String.format("￥%s", price));

        List<ProductCartModel> productCartModelList = JSONArray.parseArray(JSONArray.toJSONString(mProductCartModelList), ProductCartModel.class);
        ProductConst.getInstance().setProductCartModelList(productCartModelList);

//            List<ProductCartModel> productCartModelList = new ArrayList<>();
        mProductCartModel = new ProductCartModel();
        MacMainpSbruanDinnerEntity dinnerEntity = leftBmcmAdapter.getDinner();
        if (dinnerEntity != null) {
            mProductCartModel.setDinner(dinnerEntity.getDinner());
        } else {
            mProductCartModel.setDinner("");
        }
        mProductCartModel.setZl("9");
        mProductCartModel.setNumber(1);
        mProductCartModel.setName("现金菜");
        mProductCartModel.setPrice(price);
        mProductCartModel.setBm("xjc");
//            productCartModelList.add(productCartModel);
        if (new BigDecimal(price).compareTo(new BigDecimal(0)) == 0) {
//                ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
        } else {
            ProductConst.getInstance().getProductCartModelList().add(mProductCartModel);
            ProductConst.getInstance().setProductCartModelList(productCartModelList);
        }
        EventBus.getDefault().post(new CartEvent());
    }

    public void close() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        CardReaderDevice.getInstance().deInitCardReader();
    }

    private long lastTime = 0;

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(TimeEvent event) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        timeTv.setText("当前时间：" + simpleDateFormat.format(new Date()));

        if (lastTime == 0) {
            try {
                String cardNo = CardReaderDevice.getInstance().readCardNo();
                if (StringUtils.isEmpty(cardNo)) {
                    return;
                }
                /*if (!SystemUtils.checkCard(mContext, cardNo)) {
                    return;
                }*/
                lastTime = System.currentTimeMillis();
                cardMsgTv.setText("正在查询");
                byte[] cardSnTemp = ByteUtil.hexStringToByte(cardNo.toUpperCase());
                String cardSn = cardNo.toUpperCase();
                if(SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.reverse) {
                    byte[] b = new byte[4];
                    for (int i = 0; i < cardSnTemp.length; i++) {
                        b[i] = cardSnTemp[3 - i];
                    }
                    cardSn = ByteUtil.bytesToHexString(b);
                }

                if (SysConstConfig.getInstance().getReadCardType() == ReadCardTypeEmus.cardSQ) {
                    System.out.println("读取块" + ((SysConstConfig.getInstance().getCardDataSector() * 4) + 1));
                    System.out.println("读取的密码：" + CardReaderUtils.byteArray2HexString(SysConstConfig.getInstance().getCardSectorPass().getPassword(cardSnTemp)));
                    byte[] bReturn = CardReaderDevice.getInstance().readM1CardChunkData(0, ((SysConstConfig.getInstance().getCardDataSector() * 4) + 1),
                            SysConstConfig.getInstance().getCardSectorPass().getPassword(cardSnTemp));
                    if (bReturn != null) {
                        Log.e("TAG", "bReturn " + (SysConstConfig.getInstance().getCardDataSector() * 4)
                                + " length " + bReturn.length + " " + CardReaderUtils.byteArray2HexString(bReturn));
                        String khby1 = CardReaderUtils.byte2HexString(bReturn[0]);
                        String khby2 = CardReaderUtils.byte2HexString(bReturn[1]);
                        String khby3 = CardReaderUtils.byte2HexString(bReturn[2]);
                        int kha = Integer.parseInt(khby1, 16);
                        int khb = Integer.parseInt(khby2, 16);// 涉及到金额都要转码
                        int khc = Integer.parseInt(khby3, 16);
                        int kh = kha * 0x10000 + khb * 0x100 + khc; // 金额转码 写卡要转回来
                        System.out.println("获取卡号：" + kh);
                    } else {
                        System.out.println("方式为空");
                        cardMsgTv.setText("卡校验失败，请收回");
                        return;
                    }
                }

                RequestUtils.getFk(mContext, SystemUtils.getSerialNumber(), cardSn, new MyObserverRes<>(mContext, false) {
                    @Override
                    public void onSuccess(JSONObject result) {
                        String stringBuffer = "姓名：" + result.getString("name") + "  /  自购：" + result.getString("kye") + "  /  补贴:" + result.getString("btye");
                        cardMsgTv.setText(stringBuffer);
                        if (showCardPre != null) {
                            showCardPre.showCard(result.getString("kye"), result.getString("btye"));
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        if(e != null && e.getCause() != null) {
                            if(e.getCause().toString().contains("java.net.ConnectException")) {
                                errorMsg = "网络异常,请切换离线状态读卡";
                            }
                        }
                        cardMsgTv.setText(errorMsg);
                    }
                });
            } catch (Exception e) {
                cardMsgTv.setText("未知错误");
            }
        } else if (System.currentTimeMillis() - lastTime > 5000) {
            lastTime = 0;
            cardMsgTv.setText("");
            if (showCardPre != null) {
                showCardPre.hide();
            }
        }
    }

    public void resShow() {
        numberKey.reloadDisplaySize();
        amountTv.setText(String.format("合计：%s", ProductConst.getInstance().getProductCartPrice()));
        amountTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, SysConstConfig.getInstance().getFreeTotalAmountFontSize());
        priceTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, SysConstConfig.getInstance().getFreeInputAmountFontSize());
        inputNumberAdapter.setProductCartModelList(mProductCartModelList);
        if(!SysConstConfig.getInstance().isScanTake()) {
            scanTakeBtn.setVisibility(View.GONE);
        } else {
            scanTakeBtn.setVisibility(View.VISIBLE);
        }
        if(!SysConstConfig.getInstance().isShowRightKeyboard()) {
            rightKeyboardLinearLayout.setVisibility(View.GONE);
        } else {
            rightKeyboardLinearLayout.setVisibility(View.VISIBLE);
        }
        int size = SysConstConfig.getInstance().getInputNumberBottomButtonSize();
        int height;
        int fontSize;
        int width;
        switch (size) {
            case 0:
                width = 60;
                height = 40;
                fontSize = 20;
                break;
            case 1:
                width = 60;
                height = 60;
                fontSize = 30;
                break;
            default:
                width = 80;
                height = 80;
                fontSize = 40;
                break;
        }
        int heightInPx = (int)(height * getResources().getDisplayMetrics().density);
        int widthInPx = (int) (width * getResources().getDisplayMetrics().density);
        LayoutParams scanTakeParam = new LayoutParams(widthInPx, heightInPx);
        scanTakeParam.setMargins(0, 0, 10, 0);
        scanTakeBtn.setLayoutParams(scanTakeParam);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, heightInPx);
        params.setMargins(0, 0, 10, 0);
        payBut.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, heightInPx));
        payBut.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        netStatusRv.setLayoutParams(params);
        netStatusRv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        cancel_button.setLayoutParams(params);
        cancel_button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        addBtn.setLayoutParams(params);
        addBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
    }

    public void connectedNet() {
        netStatusRv.setText("已联网");
        netStatusRv.setBackgroundResource(R.color.green);
        netStatusRv.setTextColor(getResources().getColor(R.color.white));
    }

    public void disConnectedNet() {
        netStatusRv.setText("未联网");
        netStatusRv.setBackgroundResource(R.color.red);
        netStatusRv.setTextColor(getResources().getColor(R.color.white));
    }
}
